package com.yh.ldzl.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.PostConstruct;

import com.yh.ldzl.domain.QcRqcLine;
import com.yh.ldzl.service.IQcRqcLineService;
import com.yh.ldzl.service.QualityCheckWebSocketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.yh.ldzl.domain.QcRqc;
import com.yh.ldzl.service.IQcRqcService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;


/**
 * 退料检验单Controller
 * 
 * @author ruoyi
 * @date 2025-07-10
 */
@RestController
@RequestMapping("/qc/rqc")
public class QcRqcController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(QcRqcController.class);

    @Autowired
    private IQcRqcService qcRqcService;
    @Autowired
    private IQcRqcLineService qcRqcLineService;

    @Autowired
    private QualityCheckWebSocketService webSocketService;

    /**
     * 初始化检查
     */
    @PostConstruct
    public void init() {
        if (webSocketService == null) {
            logger.warn("警告: QualityCheckWebSocketService未正常注入，WebSocket通知功能将无法使用");
        } else {
            logger.info("QualityCheckWebSocketService注入成功，WebSocket通知功能已启用");
        }
    }

    /**
     * 查询退料检验单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(QcRqc qcRqc)
    {
        startPage();
        List<QcRqc> list = qcRqcService.selectQcRqcList(qcRqc);
        return getDataTable(list);
    }

    /**
     * 导出退料检验单列表
     */
    @Log(title = "退料检验单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QcRqc qcRqc)
    {
        List<QcRqc> list = qcRqcService.selectQcRqcList(qcRqc);
        ExcelUtil<QcRqc> util = new ExcelUtil<QcRqc>(QcRqc.class);
        util.exportExcel(response, list, "退料检验单数据");
    }

    /**
     * 获取退料检验单详细信息
     */
    @GetMapping(value = "/{rqcId}")
    public AjaxResult getInfo(@PathVariable("rqcId") Long rqcId)
    {
        return success(qcRqcService.selectQcRqcByRqcId(rqcId));
    }

    /**
     * 新增退料检验单
     */
    @Log(title = "退料检验单", businessType = BusinessType.INSERT)
    @PostMapping("/addQcRqc")
    public AjaxResult add(@RequestBody QcRqc qcRqc)
    {
        try {
            int result = qcRqcService.insertQcRqc(qcRqc);
            if (result <= 0) {
                return AjaxResult.error("新增退料检测单失败");
            }

            Long rqcId = qcRqc.getRqcId();
            logger.info("创建退料检验单成功，ID: {}, 编码: {}", rqcId, qcRqc.getRqcCode());

            // 使用WebSocket发送通知，移除RabbitMQ消息发送
            try {
                webSocketService.pushQualityCheckCreated(
                    rqcId,
                    qcRqc.getRqcCode(),
                    "4", // 退料检验对应inspectionType为4
                    "新的退料检验单已创建: " + qcRqc.getRqcName()
                );
                logger.info("WebSocket通知已发送 - 退料检验单创建: ID={}, 编码={}", rqcId, qcRqc.getRqcCode());
            } catch (Exception wsEx) {
                logger.error("发送WebSocket通知失败", wsEx);
                // 即使WebSocket通知失败，也不影响主要业务流程
            }

            return AjaxResult.success("新增退料检测单成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建退料检验单异常: {}", e.getMessage());
            return AjaxResult.error("操作异常: " + e.getMessage());
        }
    }

    /**
     * 修改退料检验单
     */
    @Log(title = "退料检验单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QcRqc qcRqc)
    {
        int rows = qcRqcService.updateQcRqc(qcRqc);
        if (rows > 0) {
            try {
                // 发送WebSocket通知，增加操作类型参数"update"
                webSocketService.pushQualityCheckUpdated(
                    qcRqc.getRqcId(),
                    qcRqc.getRqcCode(),
                    "4", // 退料检验对应inspectionType为4
                    "退料检验单已更新: " + qcRqc.getRqcName()
                );
                logger.info("WebSocket通知已发送 - 退料检验单更新: ID={}, 编码={}", qcRqc.getRqcId(), qcRqc.getRqcCode());
            } catch (Exception wsEx) {
                logger.error("发送WebSocket通知失败", wsEx);
                // 即使WebSocket通知失败，也不影响主要业务流程
            }
        }
        return toAjax(rows);
    }

    /**
     * 删除退料检验单
     */
    @Log(title = "退料检验单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{rqcIds}")
    public AjaxResult remove(@PathVariable Long[] rqcIds)
    {
        return toAjax(qcRqcService.deleteQcRqcByRqcIds(rqcIds));
    }

    /**
     * 查询退料检验单行列表
     */

    @GetMapping("/selectQcRqcLineList")
    public TableDataInfo list(QcRqcLine qcRqcLine)
    {
        logger.debug("查询退料检验单行列表参数: {}", qcRqcLine);
        startPage();
        List<QcRqcLine> list = qcRqcLineService.selectQcRqcLineList(qcRqcLine);
        return getDataTable(list);
    }
    /**
     * 新增退料检验单行
     */

    @Log(title = "退料检验单行", businessType = BusinessType.INSERT)
    @PostMapping("/addQcRqcLine")
    public AjaxResult add(@RequestBody QcRqcLine qcRqcLine)
    {
        return toAjax(qcRqcLineService.insertQcRqcLine(qcRqcLine));
    }

    /**
     * 修改退料检验单行
     */
    @Log(title = "退料检验单行", businessType = BusinessType.UPDATE)
    @PutMapping("/updateQcRqcLine")
    public AjaxResult edit(@RequestBody QcRqcLine qcRqcLine)
    {
        return toAjax(qcRqcLineService.updateQcRqcLine(qcRqcLine));
    }

    /**
     * 删除退料检验单行
     */
    @Log(title = "退料检验单行", businessType = BusinessType.DELETE)
    @DeleteMapping("deleteQcRqcLineByLineIds/{lineIds}")
    public AjaxResult deleteQcRqcLineByLineIdsRemove(@PathVariable Long[] lineIds)
    {
        return toAjax(qcRqcLineService.deleteQcRqcLineByLineIds(lineIds));
    }

    /**
     * 查询退料记录单列表
     */
    @GetMapping("/selectCkRtIssueQC")
    public AjaxResult selectQcRqcListSourceDocId(@RequestParam(value = "rt_code", required = false) String rt_code,@RequestParam(value = "rt_name", required = false) String rt_name)
    {
        startPage();
        return success(qcRqcService.selectCkRtIssueQC(rt_code,rt_name));
    }

    /**
     * 修改退料单的状态
     */
    @GetMapping("/updateCkRtIssueStatus")
    public AjaxResult updateCkRtIssueStatus(@RequestParam(value = "material_return_id", required = false) Long material_return_id)
    {
        return success(qcRqcService.updateCkRtIssueStatus(material_return_id));
    }


}
